<template>
    <div>
        <el-dialog :title="goodsinfo.isAdd ? '添加商品' : '编辑商品'" :visible.sync="goodsinfo.isShow" center @opened="createditor"
            :before-close="cancel">
            <el-form :model="goodsFrom" :rules="rules" ref="goodsRef">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select v-model="goodsFrom.first_cateid" @change="changeCate(false)">
                        <el-option v-for="item in catelist" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsFrom.second_cateid">
                        <el-option v-for="item in cateArr" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input autocomplete="off" v-model="goodsFrom.goodsname"></el-input>
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input autocomplete="off" v-model="goodsFrom.price"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input autocomplete="off" v-model="goodsFrom.market_price"></el-input>
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="handleRemove"
                        :auto-upload="false" :on-change="onChange" :file-list="fileList" :limit="1" :on-exceed="onExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select v-model="goodsFrom.specsid" @change="changeSpecs(false)">
                        <el-option v-for="item in specslist" :key="item.id" :label="item.specsname"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <el-select multiple v-model="goodsFrom.specsattr">
                        <el-option v-for="item in specsArr" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="goodsFrom.isnew" :label="1">是</el-radio>
                    <el-radio v-model="goodsFrom.isnew" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="goodsFrom.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodsFrom.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsFrom.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                        :inactive-value="2">
                    </el-switch>
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <!-- 富文本编辑器 -->
                    <div id="editor"></div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import { goodsAdd, goodsEdit, goodsInfo } from '../../request/api'
// 引入wangeditor
import E from 'wangeditor'
export default {
    props: ['goodsinfo'],
    data() {
        return {
            textarea2: '',
            formLabelWidth: '120px',
            // 控制图片预览显示隐藏
            dialogVisible: false,
            // 预览时的图片地址
            dialogImageUrl: '',
            fileList: [], //用于图片回显
            goodsFrom: {
                first_cateid: '',//一级分类编号
                second_cateid: '',//二级分类编号
                goodsname: '',//商品名称
                price: '',//商品价格
                market_price: '',//市场价格
                img: '',//商品图片（文件）
                specsid: '',//商品规格编号
                specsattr: '',//商品规格属性
                isnew: '',//是否新品 1-是 2-否
                ishot: '',//是否热卖推荐 1-是 2-否
                status: 1,//状态1正常2禁用
                description: ''//商品描述
            },
            //  规则验证
            rules: {
                first_cateid: [
                    { required: true, message: '请输入一级分类编号', trigger: 'change' },

                ],
                second_cateid: [
                    { required: true, message: '请输入二级分类编号', trigger: 'blur' }

                ],
                goodsname: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }

                ],
                market_price: [
                    { required: true, message: '请输入市场价格', trigger: 'blur' }

                ],
                specsid: [
                    { required: true, message: '请输入商品规格编号', trigger: 'change' }

                ],
                specsattr: [
                    { required: true, message: '请输入商品规格属性', trigger: 'blur' }
                ],
            },
            cateArr: [],  //二级分类
            specsArr: [],  //规格属性
            editor: null //富文本编辑器

        }
    },
    methods: {
        ...mapActions({
            getCate: 'cate/getCateListAction',
            getCount: 'goods/getCountAction',
            getGoodsList: 'goods/getGoodsListAction',
            getSpecs: 'specs/getSpecsListAction'
        }),
        // 封装一个创建富文本事件
        createditor() {
            // 创建编辑器
            this.editor = new E('#editor')
            // 创建
            this.editor.create()
            // 初始化
            this.editor.txt.html(this.goodsFrom.description)
        },
        // 封装一个一级分类切换事件，用于获取当前状态值
        changeCate(n) {
            // 知道当前id 拿id去数组中进行查找。找到所在下标 获得当前数组下标下的children
            let index = this.catelist.findIndex(item => item.id === this.goodsFrom.first_cateid)
            // console.log(index);
            this.cateArr = this.catelist[index].children
            // console.log(this.cateArr);
            // 清空二级分类双向数据绑定值
            if (!n) {
                this.goodsFrom.second_cateid = ''
            }

        },
        changeSpecs(n) {
            let index = this.specslist.findIndex(item => item.id == this.goodsFrom.specsid)
            this.specsArr = this.specslist[index].attrs
            if (!n) {
                this.goodsFrom.specsattr = ''
            }

        },
        // 文件限制方法
        onExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            )
        },
        // 预览的回调函数
        onPreview(file) {
            // 得到文件地址后赋值给要显示的属性
            this.dialogImageUrl = file.url
            // 打开预览弹框
            this.dialogVisible = true
        },
        // 移除触发的函数
        handleRemove(file, fileList) {
            console.log(file, '移除', fileList);
        },
        // 文件发生变化触发的函数
        onChange(file, fileList) {
            // console.log(file, '文件详情');
            // 把文件详情赋值给图片地址
            this.goodsFrom.img = file.raw
        },
        // 封装一个取消事件
        cancel() {
            this.$emit('cancel', false)
            this.reset()
        },
        // 清空事件
        reset() {
            this.goodsFrom = {
                first_cateid: '',//一级分类编号
                second_cateid: '',//二级分类编号
                goodsname: '',//商品名称
                price: '',//商品价格
                market_price: '',//市场价格
                img: '',//商品图片（文件）
                specsid: '',//商品规格编号
                specsattr: '',//商品规格属性
                isnew: '',//是否新品 1-是 2-否
                ishot: '',//是否热卖推荐 1-是 2-否
                status: 1,//状态1正常2禁用
                description: ''//商品描述
            }
            // 调用清空验证的方法
            this.$refs.goodsRef.resetFields()
            this.fileList = []
            // 销毁富文本编辑器
            this.editor.destroy()
        },
        // 查询一条数据
        lookUp(id) {
            goodsInfo({ id }).then(res => {
                if (res.code == 200) {
                    this.goodsFrom = res.list
                    // 图片数据回显
                    this.fileList = this.goodsFrom.img ? [{ url: this.goodsFrom.img }] : []
                    this.goodsFrom.id = id
                    // 针对规格属性进行转化
                    // this.goodsFrom.specsattr = this.goodsFrom.specsattr.split(",")
                    // 重新触发change事件实现二级联动
                    this.changeCate(true)
                    this.changeSpecs(true)
                    // 把数据重新赋值给富文本编辑器（为了严谨）
                    this.editor.txt.html(this.goodsFrom.description)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // 封装一个确定事件
        confirm() {
            this.$refs.goodsRef.validate((val) => {
                if (val) {
                    // console.log( this.goodsFrom);
                    // 规格属性进行
                    // console.log(this.goodsFrom.specsattr);//数据格式转化
                    // this.goodsFrom.specsattr = this.goodsFrom.specsattr.join(",")
                    // console.log(this.goodsFrom.specsattr);
                    // 获取富文本编辑器的内容
                    this.goodsFrom.description = this.editor.txt.html()
                    if (this.goodsinfo.isAdd) {
                        console.log(this.goodsFrom);
                        goodsAdd(this.goodsFrom).then(res => {
                            if (res.code == 200) {
                                console.log(res);
                                this.$message.success(res.msg)
                                this.cancel()
                                this.getCount()
                                this.getGoodsList()       
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    } else {
                        goodsEdit(this.goodsFrom).then(res => {
                            if (res.code == 200) {
                                // console.log(res);
                                this.$message.success(res.msg)
                                this.cancel()
                                this.getCount()
                                this.getGoodsList()       
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                }
            })
        }
    },
    mounted() {
        // 一进入页面就触发列表
        this.getCate()
        this.getSpecs()

    },
    watch: {},
    computed: {
        ...mapGetters({
            catelist: 'cate/getCateList',
            specslist: 'specs/getSpecsList'
        })
    },
    filters: {},
    components: {}
}
</script>
<style scoped></style>